package com.jqing.lib.file;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by chshqiang on 13-9-2.
 * IO流帮助类
 */
public class IOHelper {

    // 判断为一个目录是否存在，如果不存在，则创建，创建失败则返回false，创建成功则返回true，如果存在，判断是否为目录，是则返回true，否则返回false
    public static boolean isExistForDir(String path) {
        File file = new File(path);

        try {
            if (file.exists()) {
                return file.isDirectory();
            } else {
                return file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }
    }

    public static String cpInputStream(InputStream input, String name) {
        OutputStream output = null;
        String target = null;
        try {
            String outPath = Environment.getExternalStorageDirectory().getPath() + File.separator + name;
            File file = new File(outPath);
            String command = "chmod 604 " + file;
            runCommand(command);

            output = new FileOutputStream(outPath);

            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }

            target = outPath;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the streams
                if (null != output) {
                    output.flush();
                    output.close();
                }

                if (null != input) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return target;
    }

    public static boolean runCommand(String command) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (null != process) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}
